package com.xzq.bugstack.util;

import com.xzq.bugstack.domain.Constants;
import com.xzq.bugstack.domain.FileBurstData;
import com.xzq.bugstack.domain.FileBurstInstruct;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 16:27
 * @Version 1.0.0
 **/
public class FileUtil {

    public static FileBurstData readFile(String fileUrl,Integer readPosition) throws Exception {
        File file = new File(fileUrl);
        RandomAccessFile raf = new RandomAccessFile(file, "r");//r只读模式 rw读写模式
        raf.seek(readPosition);
        byte[] bytes = new byte[1024 * 10000];
        int readSize = raf.read(bytes);
        if (readSize <= 0) {
            raf.close();
            return new FileBurstData(Constants.FileStatus.COMPLETE);
        }
        FileBurstData fileInfo = new FileBurstData();
        fileInfo.setFileUrl(fileUrl);
        fileInfo.setFileName(file.getName());
        fileInfo.setBeginPos(readPosition);
        fileInfo.setEndPos(readPosition + readSize);
        //不足1024需要拷贝去掉空字节
        if (readSize < 1024 * 10000) {
            byte[] copy = new byte[readSize];
            System.arraycopy(bytes, 0, copy, 0, readSize);
            fileInfo.setBytes(copy);
            fileInfo.setStatus(Constants.FileStatus.END);
        }else {
            fileInfo.setBytes(bytes);
            fileInfo.setStatus(Constants.FileStatus.CENTER);
        }
        raf.close();
        return fileInfo;
    }

    public static FileBurstInstruct writeFile(String baseUrl, FileBurstData fileBurstData) throws Exception {
        if (Constants.FileStatus.COMPLETE == fileBurstData.getStatus()) {
            return new FileBurstInstruct(Constants.FileStatus.COMPLETE);
        }
        File file = new File(baseUrl + "/" + fileBurstData.getFileName());
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(fileBurstData.getBeginPos());
        raf.write(fileBurstData.getBytes());
        raf.close();

        if (Constants.FileStatus.END == fileBurstData.getStatus()) {
            return new FileBurstInstruct(Constants.FileStatus.COMPLETE);
        }

        //文件分片传输指令
        FileBurstInstruct fileBurstInstruct = new FileBurstInstruct();
        fileBurstInstruct.setStatus(Constants.FileStatus.CENTER);
        fileBurstInstruct.setClientFileUrl(fileBurstData.getFileUrl());
        fileBurstInstruct.setReadPosition(fileBurstData.getEndPos() + 1);   //读取位置
        return fileBurstInstruct;
    }


}
